//添加管理人账号
const express = require("express");
const route = express.Router();

//引入MongoDB集合 AdminModule
const AdminModule = require("../mongoose/module/index");
//权限控制中间件
//解析请求体中间件
route.use(express.json());
route.use(express.urlencoded());
//权限验证
const isLogin = require("../verify/isLogin");
//设置账号密码格式验证中间件
route.use("/addAdmin", isLogin, (request, response, next) => {
  //创造验证正则对象
  let { adminName, passWord, resTime } = request.body;
  const adminNameReg = /^[a-zA-Z][a-zA-Z0-9]{3,9}$/;
  const passWordRed = /^[0-9]{3,6}$/;
  if (!adminNameReg.test(adminName) || !passWordRed.test(passWord)) {
    //格式错误则直接返回出错误对象
    return response.send({
      code: 201,
      message: "账号or密码格式错误",
      data: null,
    });
  }
  next();
});

route.post("/addAdmin", async (request, response) => {
  let { adminName, passWord, resTime } = request.body;
  console.log(request);
  //查询数据库有无用户

  try {
    const user = await AdminModule.findOne({
      adminName,
    });
    if (user) {
      //存在直接返回失败
      return response.send({
        code: 202,
        message: "用户已存在",
        data: null,
      });
    }
    let createUser = await AdminModule.create(request.body);
    response.send({
      code: 200,
      message: "添加成功",
      data: createUser,
    });
  } catch (error) {
    response.send({
      code: 201,
      message: "失败",
      data: null,
    });
  }
});

//暴露addAdmin路游
module.exports = route;
